import 'package:flutter_massage/pages/model/bean.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class GetStorageService extends GetxService {
  static GetStorageService get instance => Get.find<GetStorageService>();

  static const String keyAttentionTechnician = 'key_attention_technician';
  static const String keyBlackTechnician = 'key_black_technician';

  final box = GetStorage();

  @override
  void onReady() async {
    super.onReady();
    await GetStorage.init();
  }

  ///关注、取消关注技师
  static void setAttentionTechnician(int? technicianId) async {
    TechnicianBean? bean = JsonService.getTechnicianById(technicianId);
    if (bean == null) return;
    Map<String, dynamic> json = bean.toJson();
    List<dynamic>? attentionList = instance.box.read(keyAttentionTechnician);
    attentionList ??= [];
    int index = attentionList.indexWhere((element) => element['id'] == technicianId) ?? -1;
    if (index < 0) {
      attentionList.add(json);
    } else {
      attentionList.removeWhere((element) => element['id'] == technicianId);
    }

    instance.box.write(keyAttentionTechnician, attentionList);
  }

  ///是否关注了某个技师
  static bool isAttentionTechnician(int? technicianId) {
    List<dynamic>? attentionList = instance.box.read(keyAttentionTechnician);
    attentionList ??= [];
    int index = attentionList.indexWhere((element) => element['id'] == technicianId);
    return index >= 0;
  }

  ///关注的技师列表
  static List<TechnicianBean> getAttentionTechnicianList() {
    List<dynamic>? attentionList = instance.box.read(keyAttentionTechnician);
    attentionList ??= [];
    return attentionList.map((e) => TechnicianBean.fromJson(e)).toList();
  }

  ///技师拉黑
  static Future setBlack(int? technicianId) async {
    if (technicianId == null) return;

    List? blackList = instance.box.read(keyBlackTechnician);
    blackList ??= [];
    if (!blackList.contains(technicianId)) blackList.add(technicianId);

    await instance.box.write(keyBlackTechnician, blackList);
  }

  ///拉黑列表
  static List blackList() {
    List? blackList = instance.box.read(keyBlackTechnician);
    return blackList ?? [];
  }
}
